package ar.com.ironsoft.javaopenauth.oauth.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;
import ar.com.ironsoft.javaopenauth.dto.OAuthToken;
import ar.com.ironsoft.javaopenauth.oauth.OAuthServiceV2;
import ar.com.ironsoft.javaopenauth.url.URLService;
import ar.com.ironsoft.javaopenauth.utils.ContentType;
import ar.com.ironsoft.javaopenauth.utils.ServletActionType;
import ar.com.ironsoft.javaopenauth.utils.ValidatorUtils;

public class FoursquareOAuthServiceV2 extends OAuthServiceV2 {

	private final static String urlMapping = "foursquare";

	private final static Set<ServletActionType> actions = new HashSet<ServletActionType>(
			Arrays.asList(ServletActionType.LOGIN, ServletActionType.CALLBACK));

	public FoursquareOAuthServiceV2(String clientKeysFileName) {
		super(urlMapping, actions, clientKeysFileName);
	}

	public OAuthToken getAccessToken() {
		ValidatorUtils.validateNullOrEmpty(oauthToken.getVerificationCode());
		
		String url = getAccessTokenURL();
		url = url.replace("{0}", getApiKey());
		url = url.replace("{1}", getCallbackURL());
		url = url.replace("{2}", getConsumerSecret());
		url = url.replace("{3}", oauthToken.getVerificationCode());
		
		URLService urlService = new URLService();
		Map<String,String> response = urlService.fetchUrl(url,ContentType.JSON);
		
		String accessToken = JSONObject.fromObject(response.get("json")).getString("access_token");
		
		oauthToken.setAccessToken(accessToken);
		if (response.get("expires") != null)
		oauthToken.setAccessTokenExpireTime(Integer.parseInt(response
				.get("expires")));
		
		return oauthToken;
	}
}
